// setup basic mock data
var config = require('./config/config.js');
var httpBaseUrl = 'http://localhost:' + config.http.port + config.http.baseUrl;
var async = require('async');
var showDebug = true;
var debug = (typeof showDebug !== 'undefined') ? console.log.bind(console) : function() {};

// =================================== help method
var Q = require('q');
var request = require('request');

function ajaxPost(url, json, done) {
	if (done) {
		request({
			method: 'POST',
			url: url,
			body: json,
			json: true,
			headers: {
				"content-type": "application/json"
			}
		}, function(err, res, body) { // body is object
			done(err, body);
		});
	} else {
		var defer = Q.defer();
		request({
			method: 'POST',
			url: url,
			body: json,
			json: true,
			headers: {
				"content-type": "application/json"
			}
		}, function(err, res, body) { // body is object
			if (err) defer.reject(err);
			else defer.resolve(body);
		});
		return defer.promise;
	}
}

// =================================== step clear all collection
var MongoClient = require('mongodb').MongoClient;
var mongouri = "mongodb://127.0.0.1:27017/forumv3";

function dropAllCollection(stepDone) {
	// MongoClient.connect(mongouri, function(err, db) {
	// 	if (!err) {
	// 		console.log("We are connected");
	// 	}
	// 	debug(db);
	// 	debug(db.collectionNames); // undefind
	// });
	stepDone(null, 'go next');
}

// =================================== step1 permissions
var urlPermission = httpBaseUrl + '/v1/permission';
var permissions = require('./common/all_permissions.js');

function addPermission(stepDone) {
	debug('[x] =============== ' + arguments.callee.name);
	var keys = Object.keys(permissions);
	var funList = keys.map(function(key) {
		return function(next) {
			var item = permissions[key];
			ajaxPost(urlPermission, {
				code: item[0],
				name: item[1],
				description: item[2],
			}, function(err, body) {
				next(err, body);
			});
		}
	});

	async.parallel(funList, function(err, results) {
		if (err) throw err;
		// debug(results);
		stepDone(null, results);
	});
}

// =================================== step2 roles
var urlRole = httpBaseUrl + '/v1/role';

function addRole(stepDone) {
	var keys = Object.keys(permissions);
	var permissionsCode = keys.map(function(key) {
		return permissions[key][0];
	});
	debug('permissionsCode', permissionsCode.join(','));
	var role = {
		"name": "super_admin", // cannot change it
		"description": "super admin",
		"permissions": permissionsCode
	};
	debug('[x] =============== ' + arguments.callee.name);
	ajaxPost(urlRole, role, function(err, body) {
		debug(body);
		roleSuperAdminId = body.result._id.toString();
		stepDone(null, body);
	});
}

// =================================== step orgnization
var urlOrgnization = httpBaseUrl + '/v1/orgnization/tree';
var org = {
	"name": "默认根节点",
	"description": "默认根节点",
	"isRoot": 1,
	"path": [],
	"sub": [{
		"name": "foo",
		"description": "node1",
		"sub": [{
			"name": "foobar",
			"description": "node3",
		}]
	}, {
		"name": "bar",
		"description": "node2",
	}]
};

function addOrgnization(stepDone) {
	debug('[x] =============== ' + arguments.callee.name);
	ajaxPost(urlOrgnization, org, function(err, body) {
		debug(body);
		for (var node of body.result) {
			if (node.isRoot) {
				orgnizationRootId = node._id;
				break;
			}
		}
		// orgnizationRootId = body.result._id.toString();
		stepDone(null, body);
	});
}

// =================================== step user
var urlUser = httpBaseUrl + '/v1/user';
var orgnizationRootId = null;
var roleSuperAdminId = null;
var userSuperAdmin = {
	"email": "aa@bb.com",
	"isSuperAdmin": 1,
	"phone": "13144025450",
	"name": "wzq",
	"password": "abc123",
	"rps": [{
		"orgnization": "root",
		"roles": []
	}]
};

function addUser(stepDone) {
	debug('[x] =============== ' + arguments.callee.name);
	userSuperAdmin.rps[0].orgnization = orgnizationRootId;
	userSuperAdmin.rps[0].roles.push(roleSuperAdminId);
	debug(JSON.stringify(userSuperAdmin));
	ajaxPost(urlUser, userSuperAdmin, function(err, body) {
		debug(JSON.stringify(body));
		stepDone(null, body);
	})
}

async.series([
	dropAllCollection,
	addPermission,
	addRole,
	addOrgnization,
	addUser
], function allDone(err, results) {
	if (err) {
		throw err;
	} else {
		// debug('allDone', results);
	}
});